package com;

import org.omg.CORBA.PRIVATE_MEMBER;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class ChargenServer {

    private final static int DEFAULT_PORT = 1119;

    private final static int THREAD_NUM = 50;

    private int port;

    public ChargenServer(int port) {
        this.port = port;
    }

    public void start(){

        //这里不用线程池，因此持续等待客户端断开连接
        //ExecutorService tp = Executors.newFixedThreadPool(THREAD_NUM);

        try (ServerSocket server = new ServerSocket(port)){

            while (true){

                Socket conn = server.accept();

                //tp.submit(new ChargenThread(conn));

                new Thread(new ChargenThread(conn)).start();

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {

        ChargenServer server = null;

        if(args.length == 0){
            server = new ChargenServer(DEFAULT_PORT);
        }else{
            server = new ChargenServer(Integer.parseInt(args[0]));
        }

        server.start();

    }

    public class ChargenThread implements Runnable{

        private Socket conn;

        private final static int START_ASCII = 33;

        private final static int VISIBLE_NUM = 94;

        private final static int OUT_NUM = 72;

        public ChargenThread(Socket conn) {
            this.conn = conn;
        }

        @Override
        public void run() {

            try {
                Writer writer = new OutputStreamWriter(conn.getOutputStream(),"US-ASCII");

                StringBuilder sb = new StringBuilder();

                for(int i=0;;i++){

                    int start = i%(VISIBLE_NUM-OUT_NUM+1) + START_ASCII;

                    for(int j = start;j<start+OUT_NUM;j++){

                        sb.append((char)j);

                    }

                    sb.append("\r\n");

                    writer.write(sb.toString());

                    writer.flush();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
